package com.bazaaroid.client.web.gwt.partnermodule.client.view.products;

import com.bazaaroid.client.web.gwt.partnermodule.client.dto.ProductDTO;
import com.bazaaroid.client.web.gwt.partnermodule.client.view.common.TitleCommandBar;
import com.bazaaroid.client.web.gwt.partnermodule.client.view.products.impl.ProductsTabViewImpl;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RichTextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class EditProductEntryView extends Composite {

	private ProductsTabViewImpl productsTabView;
	private ProductDTO productDTO;
	private ProductEntryView productEntryView;
	private TitleCommandBar titleBar = new TitleCommandBar("New Product");
	private TextBox nameTextBox = new TextBox();
	private RichTextArea descriptionTextArea = new RichTextArea();
	
	private class SaveClickHandler implements ClickHandler {
		@Override
		public void onClick(ClickEvent event) {
			productDTO.setName(nameTextBox.getText());
			productDTO.setDescription(descriptionTextArea.getHTML());
			productsTabView.onProductEntrySaved(productEntryView, EditProductEntryView.this, productDTO);
		}
	}
	
	private class CancelClickHandler implements ClickHandler {
		@Override
		public void onClick(ClickEvent event) {
			if(productEntryView != null) 
				productEntryView.getProductsTabView().endEdit(EditProductEntryView.this, productEntryView);
			else 
				removeFromParent();
		}
	}
	
	public EditProductEntryView(ProductsTabViewImpl productsTabView, ProductDTO productDTO) {
		this.productsTabView = productsTabView;
		this.productDTO = productDTO;
		
		VerticalPanel editProductPanel = new VerticalPanel();
		initWidget(editProductPanel);
		
		titleBar.addCommand("Save", new SaveClickHandler());
		titleBar.addCommand("Cancel", new CancelClickHandler());
		editProductPanel.add(titleBar);
		
		editProductPanel.add(new Label("Name"));
		editProductPanel.add(nameTextBox);
		editProductPanel.add(new Label("Description"));
		editProductPanel.add(descriptionTextArea);
		editProductPanel.setStyleName("productPanel");
	}
	
	public EditProductEntryView(ProductEntryView productEntryView) {
		this(productEntryView.getProductsTabView(),productEntryView.getProductDTO());
		this.productEntryView = productEntryView;
		
		titleBar.setTitle("Edit Product");
		nameTextBox.setText(productDTO.getName());
		descriptionTextArea.setHTML(productDTO.getDescription());
		
	}

}
